/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package DAO;

import entidad.Actor;
import entidad.Artist;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.swing.JOptionPane;

/**
 *
 * @author Juan
 */
public class ArtistDAO {

    public boolean crear(Artist artist) {
        boolean respuesta=false;
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAPracticePU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        try {
            em.persist(artist);
            em.getTransaction().commit();
            respuesta=true;
        } catch (Exception e) {
            em.getTransaction().rollback();
            JOptionPane.showMessageDialog(null, e);
        } finally {
            em.close();
            return respuesta;
        }
    }
    
    public void editArtist (String name, String lastName, String lugarNac, Date fechaNac, int id){
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAPracticePU");
        EntityManager em = emf.createEntityManager();
        Artist artist = em.find(Artist.class, id);
        em.getTransaction().begin();
       try{
          artist.setName(name);
          artist.setLastName(lastName);
          artist.setBirthPlace(lugarNac);
          artist.setBirthDate(fechaNac);
          em.getTransaction().commit();
          JOptionPane.showMessageDialog(null, "Edición exitosa");
      }   
        catch(Exception e){
            JOptionPane.showMessageDialog(null, e);
        }
    }
    
    public List<Artist> buscar(String nombre){
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAPracticePU");
        EntityManager em = emf.createEntityManager();
        try{
        //Case sensitive Query, needs to be replaced.
        Query q=em.createQuery("SELECT m from Artist m where lower(m.name) like lower(:nombre) or lower(m.lastName) like lower(:nombre)").setParameter("nombre","%"+nombre+"%");
        return (List<Artist>) q.getResultList();
        }
        catch(Exception e){
            JOptionPane.showMessageDialog(null, e);
            return null;
        }
    }
}
    